package com.example.rlw.mvpplugintest.downfile;

import android.os.Environment;

import com.example.rlw.mvpplugintest.mvp.BaseView;
import com.example.rlw.mvpplugintest.net.ApiException;
import com.example.rlw.mvpplugintest.net.ExceptionUtils;

import java.io.File;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

/**
 * 描述：下载文件时的observer 对象
 * Created by rlw on 2019/3/4.
 */
public abstract class DownloadFileObsever implements Observer<ResponseBody> {
    private static String FILE_PATH = Environment.getExternalStorageDirectory() + "/DownloadFile";
    private BaseView mBaseView;
    private String fileName;

    public DownloadFileObsever(BaseView baseView, String fileName) {
        mBaseView = baseView;
        this.fileName = fileName;
    }

    @Override
    public void onSubscribe(Disposable d) {
    }

    @Override
    public void onNext(ResponseBody responseBody) {
        File file = FileUtils.saveFile(FILE_PATH, fileName, responseBody);
        if (file != null && file.exists()) {
            onSuccess(file);
        } else {
            mBaseView.showFailureView(1001, "file is null or file not exists");
        }
    }

    @Override
    public void onError(Throwable e) {
        ApiException apiException = ExceptionUtils.handleException(e);
        mBaseView.showFailureView(apiException.getCode(), apiException.getMsg());
    }

    @Override
    public void onComplete() {

    }

    public abstract void onSuccess(File file);
}
